package cn.darven.xslt;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author darven
 * @date 2025/11/3
 * @description xlst 转换器
 */
public class XsltTransformer {

    public void transformToHtmlFile(String xmlContent, String xslPath, String outputPath) {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        try {
            // 加载xsl文件
            StreamSource streamSource = new StreamSource(new File(xslPath));
            Transformer transformer = transformerFactory.newTransformer(streamSource);

            // 加载xml内容
            StreamSource xmlSource = new StreamSource(new StringReader(xmlContent));
            // html
            StreamResult streamResult = new StreamResult(new File(outputPath));
            // 输出
            transformer.transform(xmlSource, streamResult);

        } catch (TransformerConfigurationException e) {
            throw new RuntimeException("创建转化器失败", e);
        } catch (TransformerException e) {
            throw new RuntimeException("转化失败", e);
        }
    }

    public String transformToHtmlContent(String xmlContent, String xslPath) {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        try {
            // 加载xsl文件
            StreamSource streamSource = new StreamSource(new File(xslPath));
            Transformer transformer = transformerFactory.newTransformer(streamSource);

            // 加载xml内容
            StreamSource xmlSource = new StreamSource(new StringReader(xmlContent));
            // html
            StringWriter writer = new StringWriter();
            StreamResult streamResult = new StreamResult(writer);
            // 输出
            transformer.transform(xmlSource, streamResult);
            return writer.toString();
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException("创建转化器失败", e);
        } catch (TransformerException e) {
            throw new RuntimeException("转化失败", e);
        }
    }

    public String formatXml(String xml) {
        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            StringReader reader = new StringReader(xml);
            StringWriter writer = new StringWriter();

            transformer.transform(new StreamSource(reader), new StreamResult(writer));
            return writer.toString();
        } catch (Exception e) {
            return xml; // 格式化失败时返回原始XML
        }
    }
}
